<!--
 * @Description: 
 * @version: 
 * @Author: 尹鹏孝
 * @Date: 2022-01-12 15:19:21
 * @LastEditors: 尹鹏孝
 * @LastEditTime: 2022-01-12 15:48:14
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数组树形化</title>
</head>

<body>
    <script>
        let data = [];
        for (let i = 1; i <= 1000; i++) {
            let obj = {
                id: i,
                pid: i - 1 == 0 ? '' : i - 1
            }
            data.push(obj);
        }

        //要求做出一个函数能够实现将此数据树形化。类似：
        /*输出： 
        [{
             id: 1,
             pid: '',
             name: 'name-1',
             children: [{
                 id: 2,
                 pid: i,
                 name: 'name-2',
                 children: [{
                     id: 3,
                     pid: 2,
                     name: 'name-3'
                 }]
             }]
         }]
         */
        function treeData(arr, child = 'children') {
            let result = [];
            if (Array.isArray(arr) && arr.length) {
                let ctrArr = JSON.parse(JSON.stringify(arr));
                let middle = {};
                ctrArr.forEach(el => {
                    middle[el.id] = el;
                    el[child] = [];
                    if (el.pid === '') {
                        result.push(el);
                    } else {
                        middle[el.pid][child].push(el);
                    }
                })
            }
            return result;
        }

        let myTestData = treeData(data);
        console.log(myTestData);


    </script>
</body>

</html>